﻿using System;
using System.Data;
using msBsc.AppLogic.DataAlc;

namespace msBsc.WebUi
{
    public partial class wfCustomerFinder : msBsc.Cls.BPageHt
    {

        //CBizShpCommercialTenantInfo objShpCommercialTenantInfo = new CBizShpCommercialTenantInfo();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();
                //System.Random rd = new Random();
                //sRadom.Value = this.GetRadomString();
            }
        }

        private void BindControls()
        {
            if (!IsPostBack)
            {
                //DataSet ds;
                //using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                //{
                //    ds = oCDbAccess.QueryBySQL("SELECT FLOOR_ID,MAIN_GOODS_NME FROM SHP_GOODS_FLOOR");
                //    ds.Tables[0].TableName = "SHP_GOODS_FLOOR";

                //}
                //BoundComboBox("FLOOR_ID", ds, "MAIN_GOODS_NME", "FLOOR_ID", "", "", true);
            }
        }
        //重构基类的回调处理函数，以strAction属性来判断是什么类型的回调，该变量的值对应前台的ACTION参数，如：按钮的名称等
        public override void InitialByParam()
        {
            if (this.gtGridRet != null)
            {
                if (this.gtGridRet.action == "load" || this.gtGridRet.action == "export")//处理GRID的数据原获取和数据导出
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    if (ds != null && ds.Tables.Count > 0)
                        SetReturnDatatable(ds.Tables[0], "CUSTOMER_REGISTER_ID");//CONSTANT_CATEGORY_ID为表的KEY字段，可填可不填
                }
                //处理数据保存
                if (this.gtGridRet.action == "save" && (gtGridRet.insertedRecords.Length > 0 || gtGridRet.updatedRecords.Length > 0 || gtGridRet.deletedRecords.Length > 0))
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    try
                    {
                        if (ds != null && ds.Tables.Count > 0)
                        {

                            //处理记录更新，前台已传入更新的ROW
                            for (int i = 0; i < gtGridRet.updatedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.updatedRecords[i]["CUSTOMER_REGISTER_ID"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("CUSTOMER_REGISTER_ID='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.updatedRecords[i], arrtemr[0]);
                                    }
                                }
                            }

                            //处理记录删除，前台已传入删除的ROW
                            for (int i = 0; i < gtGridRet.deletedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.deletedRecords[i]["CUSTOMER_REGISTER_ID"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("CUSTOMER_REGISTER_ID='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        arrtemr[0].Delete();
                                    }
                                }
                            }
                            if (ds.HasChanges())
                            {
                                System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                                transactionOption.Timeout = new TimeSpan(0, 10, 0);
                                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                                {

                                    using (msBsc.AppLogic.DataAlc.CBizCustomerRegister objtem1 = new msBsc.AppLogic.DataAlc.CBizCustomerRegister())
                                    {
                                        objtem1.Update(ds);
                                    }



                                    //objBseDataSyn.Update(ds, "PROJECT_NME,CLASS_NME,TO_SERVER_NME", false);
                                    ds.AcceptChanges();

                                    ts.Complete();
                                    ts.Dispose();

                                    //using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                                    //{
                                    //    string strmtem111 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase;
                                    //    System.Web.Routing.RouteTable.Routes.Clear();
                                    //    System.Data.DataSet ds2 = oCDbAccess.QueryBySQL("SELECT USER_NME,LEVEL_ONE_NME,SHOW_PAGE_URL FROM SHP_GOODS_TYPE_LEVEL_ONE");
                                    //    for (int i = ds2.Tables[0].Rows.Count - 1; i >= 0; i--)
                                    //    {
                                    //        System.Web.Routing.RouteTable.Routes.Add("myRoute" + i.ToString(), new System.Web.Routing.Route(ds2.Tables[0].Rows[i]["SHOW_PAGE_URL"].ToString(), new System.Web.Routing.PageRouteHandler("~" + strmtem111 + (ds2.Tables[0].Rows[i]["OLD_URL"].ToString().StartsWith("/") ? ds2.Tables[0].Rows[i]["OLD_URL"].ToString().Substring(1) : ds2.Tables[0].Rows[i]["OLD_URL"].ToString()))));
                                    //    }
                                    //} 
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ds.RejectChanges();
                        gtGridRetSaveException = err.Message;
                    }
                }
                if (gtGridRetSaveSuccess && (this.gtGridRet.action == "save" || strAction == "btnSave"))//根据传入的回调类型进行处理，这里响应编辑按钮
                {
                    //保存后将页面置为查看状态
                    SetMode("VIEW");
                }
            }
            else if (strAction == "btnEdit")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("EDIT");
            }
            else if (strAction == "btnNotSave")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("VIEW");
            }
            else if (strAction == "btnUpPass")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetPws(this.GetParamHtValue("CHECK_ID"));
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnConfirm")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "True");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnCancel")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "False");
                this.ExecJScript("btnDo('mFinder');");
            }

            base.InitialByParam();
        }
        private void SetItemStatus(string strIds, string strStatus)
        {
            using (msBsc.AppLogic.DataAlc.CBizSysUser objCBizSysUser = new AppLogic.DataAlc.CBizSysUser())
            {
                DataSet ds = objCBizSysUser.SelectByIds(strIds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["REC_ACTIVE"].ToString() != strStatus)
                    {
                        ds.Tables[0].Rows[i]["REC_ACTIVE"] = strStatus == "True";
                    }
                }
                if (ds.HasChanges())
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        objCBizSysUser.Update(ds);
                        ds.AcceptChanges();

                        ts.Complete();
                        ts.Dispose();
                    }
                }
            }
        }

        private void SetPws(string strIds)
        {
            using (msBsc.AppLogic.DataAlc.CBizCustomerRegister objCBizSysUser = new AppLogic.DataAlc.CBizCustomerRegister())
            {
                DataSet ds = objCBizSysUser.SelectByIds(strIds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["CUSTOMER_REGISTER_PWD"].ToString().Length < 22)
                    {
                        ds.Tables[0].Rows[i]["CUSTOMER_REGISTER_PWD"] = msBsc.AppLogic.Cfg.DesCry.encMe(ds.Tables[0].Rows[i]["CUSTOMER_REGISTER_PWD"].ToString(), "zbhpass");
                    }
                }
                if (ds.HasChanges())
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        objCBizSysUser.Update(ds);
                        ds.AcceptChanges();

                        ts.Complete();
                        ts.Dispose();
                    }
                }
            }
        }
        //修改页面状态
        private void SetMode(string strMode)
        {
            EditMode = strMode; switch (strMode)
            {
                case "EDIT":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", true);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "ADD":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "VIEW":
                    EnabledLinkBtn("btnEdit", true);
                    EnabledLinkBtn("btnSave", false);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", true);
                    EnabledLinkBtn("btnCancel", true);
                    this.ExecJScript("doCancelGt('myGrid1');");
                    break;
            }
        }
        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID, string strSrcF, string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                if (strSrcF == "mFinder" || !this.SessionIsExists(strsRadom + "DP_DATA", "1"))//点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                {
                    //string strCOMM_TENANT = this.GetParamHtValue("COMM_TENANT");
                    //string strLEVEL_ONE = this.GetParamHtValue("LEVEL_ONE");
                    //using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                    //{
                    //    ds = oCDbAccess.QueryBySQL("SELECT * FROM SHP_GOODS_TYPE_LEVEL_ONE WHERE LEVEL_ONE_NME LIKE '%" + strLEVEL_ONE + "%' AND  SHOW_PAGE_URL LIKE '%" + strURL_CDE + "%'");
                    //    ds.Tables[0].TableName = "SHP_GOODS_TYPE_LEVEL_ONE";
                    //} 
                    using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo objCBizShpCustomerInfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                    {
                        string sqlString = @"SELECT
A.CUSTOMER_REGISTER_ID
,A.CUSTOMER_REGISTER_ACCOUNT
,A.CUSTOMER_REGISTER_TIME
,ACCOUNT_TYPE=CASE A.CUSTOMER_ACCOUNT_TYPE WHEN 1 THEN '游客' WHEN 2 THEN '地接客' WHEN 3 THEN '管理员' END 
,A.CUSTOMER_NICK
,A.CUSTOMER_INVITATION_CODE 
,B.CUSTOMER_BASEINFO_NAME
,B.CUSTOMER_BASEINFO_PHONE
,B.CUSTOMER_BASEINFO_MOBILE
,B.CUSTOMER_BASEINFO_QQ
,B.CUSTOMER_BASEINFO_EMAIL
,B.CUSTOMER_WECHAT_NO
,CUSTOMER_GENDER = CASE B.CUSTOMER_BASEINFO_GENDER WHEN 'F' THEN '女' WHEN 'M' THEN '男' ELSE '' END 
FROM DJK_CUSTOMER_REGISTER A LEFT OUTER JOIN DJK_CUSTOMER_BASEINFO B ON A.CUSTOMER_REGISTER_ID=B.CUSTOMER_BASEINFO_ID
WHERE A.CUSTOMER_ACCOUNT_TYPE=1";

                        string parmValue = this.GetParamHtValue("USER_NME");
                        string parmValue1 = this.GetParamHtValue("UTYP_ACTIVE");

                        if (parmValue1 != string.Empty)
                        {
                            sqlString += parmValue1 == "1" ? " AND A.CUSTOMER_ACCOUNT_RMK IS NULL" : "";
                        }


                        sqlString += parmValue == string.Empty ? "" : " AND A.CUSTOMER_REGISTER_ACCOUNT LIKE %" + parmValue + "% OR A.CUSTOMER_REGISER_NICK LIKE %" + parmValue + "% OR B.CUSTOMER_BASEINFO_NAME LIKE %" + parmValue + "%";
                        sqlString += " ORDER BY A.CUSTOMER_REGISTER_TIME";
                        ds = objCBizShpCustomerInfo.DataObj.QueryBySQL(sqlString);
                        //+ (this.GetParamHtValue("REC_ACTIVE") == string.Empty ? "" : " AND (REC_ACTIVE='" + this.GetParamHtValue("REC_ACTIVE") + "' )")
                        //+ (this.GetParamHtValue("FWDUSER_NME") == string.Empty ? "" : " AND (FWDUSER_NME='" + this.GetParamHtValue("FWDUSER_NME") + "')")
                        //+ (this.GetParamHtValue("PROMOTION_NME") == string.Empty ? "" : " AND (PROMOTION_NME='" + this.GetParamHtValue("PROMOTION_NME") + "')") 
                        ds.Tables[0].TableName = "DJK_CUSTOMER_REGISTER";
                        //ds = objCBizShpCustomerInfo.SelectInfoForFinder(this.GetParamHtValue("USER_NME"), this.GetParamHtValue("REC_ACTIVE"));
                        ds.AcceptChanges();
                    }
                    SetSession(strsRadom + "DP_DATA", ds, "1");
                    //查询时，将页面置为查看状态
                    if (strSrcF == "mFinder")
                        SetMode("VIEW");
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "1");
                }
                return ds;
            }
            else
            {
                return null;
            }
        }
    }
}